package com.soundfrequencyapp;

import java.util.Timer;
import java.util.TimerTask;

import android.app.Activity;
import android.content.Intent;
import android.media.AudioFormat;
import android.media.AudioRecord;
import android.media.MediaRecorder.AudioSource;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.widget.TextView;

import com.soundfrequencyapp.actions.ImageActivity;
import com.soundfrequencyapp.actions.LoadUrlActivity;
import com.soundfrequencyapp.actions.VideoActivity;

public class SoundActivity extends Activity {

	private AudioRecord recorder;
	
	private final int sampleRate = 44100;
	private final int bufferSize = 8192 * 8;
	private byte[] audioData = new byte[bufferSize];
	
	private final long interval = 1000;
	private final double frequencyDelta = 20d;
	
	private Handler handler = new Handler();
	private Timer timer;
	
	private static final double FREQUENCY_CALL_TO_NUMBER = 18000d;
	private static final double FREQUENCY_LOAD_URL = 18200d;
	private static final double FREQUENCY_SHOW_IMAGE = 18400d;
	private static final double FREQUENCY_PLAY_VIDEO = 18600d;
	private static final double FREQUENCY_SEND_SMS = 18800d;
	
	private final int phoneNumber = 2135554321;
	private final String url = "http://www.google.com";
	private final int imageId = R.raw.image;
	private final int videoId = R.raw.video;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.screen_activity_sound);
	}
	
	@Override
	protected void onResume() {
		super.onResume();
		
		setRecorder();
		
		startSoundRecording();
		
		startSoundFrequencyChecking();
	}

	@Override
	protected void onPause() {
		super.onPause();

		if (recorder != null
				&& recorder.getState() == AudioRecord.STATE_INITIALIZED) {
			recorder.release();
			recorder = null;
		}
		
		if (timer != null) {
			timer.cancel();
			timer = null;
		} 
	}

	private void setRecorder() {
		recorder = new AudioRecord(AudioSource.MIC, sampleRate,
				AudioFormat.CHANNEL_IN_MONO,
				AudioFormat.ENCODING_PCM_16BIT, bufferSize);
	}
	
	private void startSoundRecording() {
		recorder.startRecording();
	}
	
	private void startSoundFrequencyChecking() {
		timer = new Timer("frequencyTimer");
		scheduleTask();
	}
	
	private void scheduleTask() {
		TimerTask task = new TimerTask() {
			
			public void run() {
				if (isRecorderPrepared()) {
					recorder.read(audioData, 0, bufferSize);
					final double frequency = SoundUtil.calculateFrequency(audioData, bufferSize, sampleRate);
					handleFrequency(frequency);
					scheduleTask();
				}
				
			}
		};
		if (timer != null) {
			timer.schedule(task, interval);
		}
	}
	
	private void handleFrequency(final double frequency) {
		
		if (isFrequencyValueUsefull(frequency, FREQUENCY_CALL_TO_NUMBER)) {
			handler.post(new Runnable() {
				@Override
				public void run() {
					call(phoneNumber);
				}
			});
		} else if (isFrequencyValueUsefull(frequency, FREQUENCY_LOAD_URL)) {
			handler.post(new Runnable() {
				@Override
				public void run() {
					loadUrl(url);
				}
			});
		} else if (isFrequencyValueUsefull(frequency, FREQUENCY_SHOW_IMAGE)) {
			handler.post(new Runnable() {
				@Override
				public void run() {
					showImage(imageId);
				}
			});
		} else if (isFrequencyValueUsefull(frequency, FREQUENCY_PLAY_VIDEO)) {
			handler.post(new Runnable() {
				@Override
				public void run() {
					playVideo(videoId);
				}
			});
		} else if (isFrequencyValueUsefull(frequency, FREQUENCY_SEND_SMS)) {
			handler.post(new Runnable() {
				@Override
				public void run() {
					sendSms(phoneNumber);
				}
			});
		}
	}
	
	private boolean isFrequencyValueUsefull(double currValue, double etalonValue) {
		return Math.abs(currValue - etalonValue) < frequencyDelta;
	}
	
	private boolean isRecorderPrepared() {
		boolean isPrepared = recorder != null; 
		return isPrepared;
	}
	
	private void call(int phoneNumber) {
		Intent callIntent = new Intent(Intent.ACTION_CALL);
        callIntent.setData(Uri.parse("tel:" + String.valueOf(phoneNumber)));
        startActivity(callIntent);
	}
	
	private void loadUrl(String url) {
		Intent i = new Intent(this, LoadUrlActivity.class);
		i.putExtra(LoadUrlActivity.EXTRA_URL, url);
		startActivity(i);
	}
	
	private void sendSms(int phoneNumber) {
		Intent i = new Intent(Intent.ACTION_VIEW, Uri.fromParts("sms", String.valueOf(phoneNumber), null));
		startActivity(i);
	}
	
	private void showImage(int imageId) {
		Intent i = new Intent(this, ImageActivity.class);
		i.putExtra(ImageActivity.EXTRA_IMAGE_ID, imageId);
		startActivity(i);
	}
	
	private void playVideo(int videoId) {
		Intent i = new Intent(this, VideoActivity.class);
		i.putExtra(VideoActivity.EXTRA_VIDEO_ID, videoId);
		startActivity(i);
	}
	
}
